package cc.angis.xiugallery;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import cc.angis.xiugallery.account.IAccountManager;
import cc.angis.xiugallery.account.QQWeiboAccountManager;
import cc.angis.xiugallery.account.WeiboAccountManager;
import cc.angis.xiugallery.common.GlobalConst;
import cc.angis.xiugallery.common.GlobalConst.AccountType.AccountTypes;
import cc.angis.xiugallery.data.UserAccount;
import cc.angis.xiugallery.provider.UserAccountProvider;
import cc.angis.xiugallery.util.NetworkStatus;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.MenuItem;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.tencent.weibo.webview.OAuthV2AuthorizeWebView;

public class UserAccountActivity extends SherlockActivity{
	
	private UserAccountProvider userAccountProvider;
	
	private IAccountManager accountManager;
	
	private ViewGroup viewGroup; 
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.useraccount);
		ActionBar actionbar = this.getSupportActionBar();
		actionbar.setDisplayHomeAsUpEnabled(true);
		actionbar.setTitle(R.string.settings_account);
		viewGroup = (ViewGroup) findViewById(R.id.useraccountlayout);
		userAccountProvider = new UserAccountProvider(this);
		userAccountProvider.initSource();
//		if(NetworkStatus.getNetWorkStatus(getApplicationContext())>0 && userAccountProvider.getUserAccounts()!=null && userAccountProvider.getUserAccounts().size() > 0){
//			for (UserAccount userAccount : userAccountProvider.getUserAccounts()){
//				switch (userAccount.getType()){
//				case GlobalConst.AccountType.ACCOUNT_TYPE_WEIBO:
//					accountManager = new WeiboAccountManager(UserAccountActivity.this);
//					accountManager.doAuth();
//					break;
//				case GlobalConst.AccountType.ACCOUNT_TYPE_QQ:
//					accountManager = new QQWeiboAccountManager(UserAccountActivity.this);
//					accountManager.doAuth();
////					UserAccountActivity.this.startActivityForResult(new Intent(UserAccountActivity.this, SelectFavouriteActivity.class), 1);
//					break;
//				case GlobalConst.AccountType.ACCOUNT_TYPE_TWITTER:
//					break;
//				default:
//					break;
//			}
//			}
//		}
		addAccountViews(viewGroup);
	}

	public void addAccountViews(ViewGroup container) {
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		LinearLayout subView;
		ImageView iconView;
		TextView bindText;
		TextView nameText;
		Button bindButton;
		for (AccountTypes type : GlobalConst.AccountType.AccountTypes.values()){
			subView = (LinearLayout)inflater.inflate(R.layout.accountrow, container, false);
			iconView = (ImageView)subView.findViewById(R.id.account_icon);
			bindText = (TextView) subView.findViewById(R.id.account_bind);
			nameText = (TextView) subView.findViewById(R.id.account_name);
			bindButton = (Button) subView.findViewById(R.id.bind_button);
			if (type.ordinal() == GlobalConst.AccountType.ACCOUNT_TYPE_WEIBO){
				iconView.setImageResource(R.drawable.weiboicon);
				bindText.setText(R.string.account_weibo);
			} else if (type.ordinal() == GlobalConst.AccountType.ACCOUNT_TYPE_TWITTER){
				iconView.setImageResource(R.drawable.twittericon);
				bindText.setText(R.string.account_twitter);
			} else if (type.ordinal() == GlobalConst.AccountType.ACCOUNT_TYPE_QQ){
				iconView.setImageResource(R.drawable.qqicon);
				bindText.setText(R.string.account_qq);
			}
			if (userAccountProvider.hasUserAccount(type.ordinal())){
				nameText.setText(userAccountProvider.getUserAccount(type.ordinal()).getUsername());
//				nameText.setVisibility(View.VISIBLE);
				bindButton.setBackgroundResource(R.drawable.binded);
				bindButton.setOnClickListener(new UnBindOnClickListener(type.ordinal()));
			} else {
//				nameText.setVisibility(View.GONE);
				bindButton.setBackgroundResource(R.drawable.bind_button);
				bindButton.setOnClickListener(new BindOnClickListener(type.ordinal()));
			}
			LinearLayout.LayoutParams lp = (LayoutParams) subView.getLayoutParams();
			lp.setMargins(0, getResources().getDimensionPixelSize(R.dimen.account_row_margin), 0, 0);
			container.addView(subView);
		}
		
//					try {  
//						Twitter twitter = new TwitterFactory().getInstance(); 
//						twitter.setOAuthConsumer(GlobalConst.TWITTER_CONSUMER_KEY, GlobalConst.TWITTER_CONSUMER_SECRET);
//						RequestToken requestToken = twitter.getOAuthRequestToken(CALLBACKURL);  
//			            getActivity().startActivity(new Intent(Intent.ACTION_VIEW,  
//			            Uri.parse(requestToken.getAuthenticationURL())));  
//					} catch (TwitterException e) {  
//			            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.  
//			        }  
	}
	
	class BindOnClickListener implements OnClickListener {
		private int type;
		
		public BindOnClickListener(int type){
			this.type = type;
		}

		@Override
		public void onClick(View v) {
			if(NetworkStatus.getNetWorkStatus(getApplicationContext())<=0){
				Toast.makeText(getApplicationContext(), R.string.toast_nonetwork, Toast.LENGTH_SHORT).show();
				return;
			}
				
			switch (type){
				case GlobalConst.AccountType.ACCOUNT_TYPE_WEIBO:
					accountManager = new WeiboAccountManager(UserAccountActivity.this);
					accountManager.doAuth();
					break;
				case GlobalConst.AccountType.ACCOUNT_TYPE_QQ:
					accountManager = new QQWeiboAccountManager(UserAccountActivity.this);
					accountManager.doAuth();
//					UserAccountActivity.this.startActivityForResult(new Intent(UserAccountActivity.this, SelectFavouriteActivity.class), 1);
					break;
				case GlobalConst.AccountType.ACCOUNT_TYPE_TWITTER:
					break;
				default:
					break;
			}
		}
		
	}
	
	class UnBindOnClickListener implements OnClickListener {
		private int type;
		
		public UnBindOnClickListener(int type){
			this.type = type;
		}

		@Override
		public void onClick(View v) {
//			if(NetworkStatus.getNetWorkStatus(getApplicationContext())<=0){
//				Toast.makeText(getApplicationContext(), R.string.toast_nonetwork, Toast.LENGTH_SHORT).show();
//				return;
//			}
			doUnbind(type);
		}
		
	}
	
	private void doUnbind(final int type){
		AlertDialog.Builder builder = new AlertDialog.Builder(UserAccountActivity.this);
		builder.setTitle(R.string.dialog_unauthorize)
		.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (type){
					case GlobalConst.AccountType.ACCOUNT_TYPE_WEIBO:
						accountManager = new WeiboAccountManager(UserAccountActivity.this);
						accountManager.unbind();
						break;
					case GlobalConst.AccountType.ACCOUNT_TYPE_QQ:
						accountManager = new QQWeiboAccountManager(UserAccountActivity.this);
						accountManager.unbind();
	//					UserAccountActivity.this.startActivityForResult(new Intent(UserAccountActivity.this, SelectFavouriteActivity.class), 1);
						break;
					case GlobalConst.AccountType.ACCOUNT_TYPE_TWITTER:
						break;
					default:
						break;
				}
				onCreate(null);
				
			}

		}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				
			}

		}).show();
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)   {
        if (requestCode==1) {
            if (resultCode==OAuthV2AuthorizeWebView.RESULT_CODE)    {
            	if (accountManager !=null && accountManager instanceof QQWeiboAccountManager){
            		((QQWeiboAccountManager)accountManager).doAuth2((OAuthV2) data.getExtras().getSerializable("oauth"));
            	}
            }
        }
    }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			this.finish();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	

}
